package com.example.demo2;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RequestMapping("/cs")
@RestController
public class CookieSession {
    @RequestMapping("/c1")
    public String h1(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
      if (cookies!=null){
          for (Cookie cookie:cookies) {
              System.out.println("key:"+cookie.getName()+"     val:"+cookie.getValue());
          }
          return "返回Cookie成功";
      }
return "返回cookie失败";
    }

    @RequestMapping("c2")
    public String c2(@CookieValue("age") String age){
        return "获取Cookie中age的值："+age;
    }

    @RequestMapping("/s1")
public String s1(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("userName","zhangsan");
        session.setAttribute("age",17);
        return "设置session成功";
    }

    @RequestMapping("/s2")
    public String s2(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session==null){
            return "用户未登录";
        }else {
            String userName = (String)session.getAttribute("userName");
return "登陆用户为："+userName;
        }
    }

    @RequestMapping("/s3")
    public String s3(HttpSession session){
        if(session==null){
            return "用户未登录";
        }else {
            String userName = (String)session.getAttribute("userName");
            return "登陆用户为："+userName;
        }
    }

    @RequestMapping("/s4")
    public String s3(@SessionAttribute("userName")String userName){
            return "登陆用户为："+userName;
    }


}
